<?php

defined('IN_XLP') or exit('Access Denied');

class apiModel extends model {

    function __construct() {
        parent::__construct();
    }

    /*
     * 用户注册
     */

    public function signUp($phone, $passwd) {
        $rs = M('user_detail')->field('`phone_real`')->where(array('phone_real' => $phone))->find();
        if ($rs) {
            return false;  //手机号已被占用
        }

        $salt = getRandStr(6, true);
        $passwd = md5($passwd . sha1($salt));
        $uid = M('user')->insert(
                array(
                    'phone' => $phone,
                    'password' => $passwd,
                    'nickname' => "手机用户" . $phone,
                    'reg_time' => TIME,
                    'reg_ip' => ip2long(getUserIp()),
                    'status' => 1,
                    'salt' => $salt,
                )
        );
        $detail = array(
            'headimgurl' => '',
            'unionid' => '',
            'subscribe' => 1,
            'uid' => $uid,
            'nickname' => '',
            'sex' => '',
            'city' => '',
            'country' => '',
            'province' => '',
            'language' => '',
            'subscribe_time' => TIME
        );
        D('member')->setUserDetail($detail);
        M('user_detail')->update(array('phone_real' => $phone), array('uid' => $uid));
        return $uid;
    }

    /*
     * 用户登录
     */

    public function signIn($phone, $passwd) {
        $rs = M('user')
                ->field('`uid`,`phone`,`password`,`salt`')
                ->where(array('phone' => $phone))
                ->find();
        if ($rs) {
            $passwd = md5($passwd . sha1($rs['salt']));
            if (strcmp($passwd, $rs['password']) === 0) {
                return $rs['uid'];
            } else {
                return 0;   //密码不对
            }
        } else {
            return -1;  //该手机尚未注册
        }
    }

    /*
     * 微信登录
     */

    public function weixinLogin($info) {
        //$info['unionid']=$info['unionid']."s";
        //是否公众号老用户
        $rs = M('user_bind')
                ->field('`uid`')
                ->where(array('type' => "wx", 'unionid' => $info['unionid']))
                ->find();
        if ($rs) {
            return $rs['uid'];
        } else {
            //是否微信APP老用户
            $rss = M('user_bind')
                    ->field('`uid`')
                    ->where(array('type' => "wx_app", 'unionid' => $info['unionid']))
                    ->find();
            if ($rss) {
                return $rss['uid'];
            } else {
                //添加用户
                $uid = M('user')->insert(
                        array(
                            'nickname' => isset($info['nickname']) ? trim(preg_replace('~\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]~', '', $info['nickname'])) : '',
                            'reg_time' => TIME,
                            'sex' => $info['sex'],
                            'reg_ip' => ip2long(getUserIp()),
                            'status' => 1
                        )
                );
                if ($uid) {
                    //添加用户详细信息
                    $bind = array(
                        'uid' => $uid,
                        'aid' => 0,
                        'type' => "wx_app",
                        'keyid' => $info['openid']
                    );
                    D('member')->addBindInfo($bind);
                    //添加用户信息
                    $detail = array(
                        'headimgurl' => $info['headimgurl'],
                        'unionid' => $info['unionid'],
                        'subscribe' => 1,
                        'uid' => $uid,
                        'nickname' => isset($info['nickname']) ? trim(preg_replace('~\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]~', '', $info['nickname'])) : '',
                        'sex' => isset($info['sex']) ? $info['sex'] : '',
                        'city' => isset($info['city']) ? $info['city'] : '',
                        'country' => isset($info['country']) ? $info['country'] : '',
                        'province' => isset($info['province']) ? $info['province'] : '',
                        'language' => isset($info['language']) ? $info['language'] : '',
                        'subscribe_time' => TIME
                    );
                    D('member')->setUserDetail($detail);
                    //头像
                    $content = getHttp($info['headimgurl'], array(), true);
                    if ($content) {
                        //保存为用户头像
                        setAvatar($uid, $content);
                    }
                    //======需要自动创建的表============
                    if (!M('user_count')->field('uid')->where(array('uid' => $uid))->find()) {
                        //生成一个用户统计表
                        $userCountObj = array();
                        //获取字段内容
                        $userCountList = M('user_count')->getTableFields();
                        foreach ($userCountList['fields'] as $key => $val) {
                            $userCountObj[$key] = $val['value'];
                        }
                        $userCountObj['uid'] = $uid;
                        M('user_count')->insert($userCountObj);
                    }
                    //======需要自动创建的表============
                    return $uid;
                } else {
                    return -1;
                }
            }
        }
    }

    /*
     * QQ登录
     */

    public function qqLogin($info) {
        $rs = M('user_bind')
                ->field('`uid`')
                ->where(array('type' => "qq", 'keyid' => $info['openid']))
                ->find();
        if ($rs) {
            return $rs['uid'];
        } else {
            //添加用户
            $uid = M('user')->insert(
                    array(
                        'nickname' => isset($info['nickname']) ? trim(preg_replace('~\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]~', '', $info['nickname'])) : '',
                        'reg_time' => TIME,
                        'sex' => $info['sex'],
                        'reg_ip' => ip2long(getUserIp()),
                        'status' => 1
                    )
            );
            if ($uid) {
                //添加用户详细信息
                $bind = array(
                    'uid' => $uid,
                    'aid' => 0,
                    'type' => "qq",
                    'keyid' => $info['openid']
                );
                D('member')->addBindInfo($bind);
                //添加用户信息
                $detail = array(
                    'headimgurl' => $info['headimgurl'],
                    'subscribe' => 1,
                    'uid' => $uid,
                    'nickname' => isset($info['nickname']) ? trim(preg_replace('~\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]~', '', $info['nickname'])) : '',
                    'sex' => isset($info['sex']) ? $info['sex'] : '',
                    'city' => isset($info['city']) ? $info['city'] : '',
                    'country' => isset($info['country']) ? $info['country'] : '',
                    'province' => isset($info['province']) ? $info['province'] : '',
                    'language' => isset($info['language']) ? $info['language'] : '',
                    'subscribe_time' => TIME
                );
                D('member')->setUserDetail($detail);
                //头像
                $content = getHttp($info['headimgurl'], array(), true);
                if ($content) {
                    //保存为用户头像
                    setAvatar($uid, $content);
                }
                //======需要自动创建的表============
                if (!M('user_count')->field('uid')->where(array('uid' => $uid))->find()) {
                    //生成一个用户统计表
                    $userCountObj = array();
                    //获取字段内容
                    $userCountList = M('user_count')->getTableFields();
                    foreach ($userCountList['fields'] as $key => $val) {
                        $userCountObj[$key] = $val['value'];
                    }
                    $userCountObj['uid'] = $uid;
                    M('user_count')->insert($userCountObj);
                }
                //======需要自动创建的表============
                return $uid;
            } else {
                return -1;
            }
        }
    }

    /**
     * 生成App微信支付参数
     * @param  String $body      订单描述
     * @param  String $out_sn    外部交易号
     * @param  String $total_fee 订单实付 注意单位为分
     * @param  Array  $others    其它非必需支付参数
     * @return String            JSON字符串 用于App端发起支付
     */
    public function wxPay($body, $out_sn, $total_fee, $others = null) {

        //去除订单名称空白字符
        $body = preg_replace('/\s/', '', $body);
        //商品描述最多128字节
        if (strlen($body) > 128) {
            $body = cnsubStr($body, 40);
        }

        $temp = array();
        $temp['body'] = $body;
        $temp['out_trade_no'] = $out_sn;
        $temp['total_fee'] = $total_fee * 100; //注意单位为分
        //其它参数
        if (is_array($others)) {
            $temp = $temp + $others;
        }

        T('weixin/weixin.app');
        try {
            $app = new weixinApp();
            $app->setOrderParams($temp);
            $json = $app->getAppParam();
        } catch (Exception $e) {
            $error_msg = $e->getMessage();
            $debug_info = $e->getTraceAsString();

            $this->errorLog($error_msg, $debug_info);
        }

        return $json;
    }

    /**
     * 删除app配置文件
     */
    public function refreshConfig() {
        F('app/appClient_config', null);
        F('app/appClient_config_timestamp', null);
        return true;
    }

    private function errorLog($msg = "", $debug = "") {
        saveLog('apiModel/error', $msg . ' ' . $debug);
        showError($msg);
    }

}
